#include "media_diagnosis.h"

#include <algorithm>
#include <future>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>

#include "base_file_util.h"
#include "base_utils.h"
#include "base_string.h"
#include "base_log.h"
#include "common_shell.h"

namespace El {
namespace Media {

CStreamDiagnosis &CStreamDiagnosis::GetInstance()
{
    static CStreamDiagnosis cLVLive;
    return cLVLive;
}

bool CStreamDiagnosis::Start()
{
    Common::Shell::GetInstance().RegisterCommand("stream",
                                                 std::bind(&CStreamDiagnosis::Record, this, std::placeholders::_1));
    return true;
}

void CStreamDiagnosis::Record(const std::string &args)
{
    LOG_INFO("Record {}", args.c_str());

    // 解析args字段，获取参数，分别是：channel、stream_type、start
    std::vector<std::string> vecArgs;
    Base::Split(args, " ", vecArgs);
    if (vecArgs.size() < 3) {
        LOG_ERROR("Invalid args: {}", args.c_str());
        return;
    }
    int32_t ch = std::stoi(vecArgs[0]);
    int32_t streamType = std::stoi(vecArgs[1]);
    if (vecArgs[2] == "start") {
        stream_ = Media::StreamSource::Create(ch, streamType);
        stream_->SetInfo(120, "stream diagnosis");
        handle_ = stream_->Register(std::bind(&CStreamDiagnosis::OnStream, this, std::placeholders::_1));
        stream_->Start();
    } else if (vecArgs[2] == "stop") {
        stream_->Stop();
        stream_.reset();
    } else {
        LOG_ERROR("Invalid command: {}", vecArgs[2].c_str());
    }
}

void CStreamDiagnosis::OnStream(const MediaFramePtr &ptr)
{
    LOG_INFO("OnStream: {}", ptr->ToString().c_str());
    std::vector<uint8_t> content(ptr->GetBuffer(), ptr->GetBuffer() + ptr->GetLength());
    if (ptr->GetFrameType() == MEDIA_FRAME_I || ptr->GetFrameType() == MEDIA_FRAME_P) {
        Base::SaveBufferToFile("/mnt/udisk/record.h264", content, false);
    } else if (ptr->GetFrameType() == MEDIA_FRAME_G711A) {
        Base::SaveBufferToFile("/mnt/udisk/record.g711a", content, false);
    }
}

} // namespace Media
} // namespace El